package com.cmcc.driver.ui.main

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.location.Location
import android.location.LocationManager
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Looper
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.DriverDataRepository
import com.cmcc.driver.data.entity.OrderDetail
import com.cmcc.driver.data.entity.OrderTemp
import com.cmcc.driver.databinding.ActivityOrderInProgressDetailBinding
import com.cmcc.driver.databinding.ActivityOrderReceiveDetailBinding
import com.cmcc.driver.ui.base.BasicActivity
import com.cmcc.driver.ui.dialog.AppAlertDialog
import com.cmcc.driver.ui.dialog.AppProgressDialog
import com.cmcc.driver.ui.main.viewmodel.OrderReceiveViewModel
import com.cmcc.driver.util.LocationUtil
import com.cmcc.shared.utils.GPSConverterUtils
import com.cmcc.shared.utils.TextViewUtil.setTextViewByLimit
import com.cmcc.shared.utils.TextViewUtil.setTextViewValue
import com.cmcc.shared.utils.TimeUtils
import com.cmcc.shared.utils.clickWithTrigger
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.google.maps.android.PolyUtil


/**
 * Author: jiangxin
 * Date: 2019/11/6
 * Description: 接单
 */
@Route(path = DriverPath.ORDER_RECEIVE_DETAIL)
class OrderReceiveDetailActivity : BasicActivity(), OnMapReadyCallback {


    private lateinit var mMap: GoogleMap
    private lateinit var binding: ActivityOrderReceiveDetailBinding

    private var viewModel: OrderReceiveViewModel? = null
    private var orderModel: OrderTemp? = null
    private var progressDialog: AppProgressDialog? = null

    private lateinit var bottomSheetBehavior: BottomSheetBehavior<LinearLayout>

    private lateinit var fusedLocationClient: FusedLocationProviderClient

    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: LocationCallback

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

//        val lat = orderModel?.startCoordinates?.longitude
//        val lng = orderModel?.startCoordinates?.longitude
//        val appointLoc = LatLng(lat ?: 0.0, lng ?: 0.0)
        val appointLoc = LocationUtil.getInstance().getCurrentLoc()
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(appointLoc, 15f))

        drawRoutes(googleMap)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        binding = DataBindingUtil.setContentView(
            this,
            R.layout.activity_order_receive_detail
        )
        binding.appbar.toolbar.setNavigationOnClickListener { finish() }
        //把地图加到fragment layout去
        val mapFragment  = SupportMapFragment()
        supportFragmentManager.beginTransaction().replace(R.id.map, mapFragment).commit();
        mapFragment?.getMapAsync(this)

        progressDialog = AppProgressDialog(this)

        bottomSheetBehavior = BottomSheetBehavior.from(binding.progress)

        viewModel = ViewModelProviders.of(this).get(OrderReceiveViewModel::class.java)

        val orderId = intent.getStringExtra("orderId")
        /**
         * 获取订单模板数据
         */
        viewModel?.getOrderTemplate(orderId ?: "")

        fusedLocationClient =
            LocationServices.getFusedLocationProviderClient(this)

        locationRequest = LocationRequest()
        locationRequest.interval =
            10 * 1000L //请求时间间隔
        locationRequest.fastestInterval =
            1500L//最快时间间隔
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                if (locationResult == null) return
                handleLocation(locationResult.lastLocation)
            }
        }


        // 在onCreate 方法中  让它默认展开状态
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)

    }

    /**
     * 获取当前位置的回调方法
     */
    private fun handleLocation(lastLocation: Location) {
        val latLng = LatLng(lastLocation.latitude, lastLocation.longitude)
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18f))

        stopLocationUpdate()
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        binding.appbar.toolbar.setNavigationOnClickListener { finish() }

        binding.appbar.title.text = getString(R.string.receive_detail_title)

        binding.appbar.profile.visibility = View.GONE


        binding.optionsLayout.nextTip1.text = getString(R.string.receive_order)
    }

    override fun initEvent(savedInstanceState: Bundle?) {
        super.initEvent(savedInstanceState)
        binding.appbar.profile.clickWithTrigger {
            ARouter.getInstance().build(DriverPath.DRIVER_PROFILE).navigation()
        }

//        binding.contactPass.clickWithTrigger {
//            AppAlertDialog(this).setContent(getString(R.string.if_you_need_call))
//                .setNavigation(getString(R.string.cancel), null)
//                .setPositive(getString(R.string.make_sure),
//                    View.OnClickListener {
////                        val data = Uri.parse("tel:852" + orderModel?.passenger?.phone)
////                        val intent = Intent(Intent.ACTION_DIAL, data)
////                        startActivity(intent)
//                    }).show()
//        }

        binding.collapsingLayout.clickWithTrigger {
            when (bottomSheetBehavior.state) {
                BottomSheetBehavior.STATE_COLLAPSED -> {//收起状态
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED

                    binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                }
                BottomSheetBehavior.STATE_EXPANDED -> {//展开状态
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED

                    binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                }
            }
        }



        bottomSheetBehavior.setBottomSheetCallback(object : BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (bottomSheetBehavior.state) {
                    BottomSheetBehavior.STATE_COLLAPSED -> {//收起状态
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                    }
                    BottomSheetBehavior.STATE_EXPANDED -> {//展开状态
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                    }

                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {}
        })

        binding.optionsLayout.nextTip1.clickWithTrigger {
            if (null != orderModel) {
                val orderId = orderModel?.id
                if (!orderId.isNullOrEmpty()) {
                    progressDialog?.show()
//                    if(orderModel?.type == 1){
                    //接单
                    viewModel?.receivingOrder(orderId)
//                    }else{
//                        viewModel?.actionOrder(orderId!!)
//                    }
                }
            }
        }
        binding.navigation.clickWithTrigger {

            val currentLatLng: LatLng? = LocationUtil.getInstance().getCurrentLoc()

            if (null != currentLatLng) {
                val current = convert(currentLatLng)
                val startLatLng = LatLng(current.lat, current.lon)

                var endLatLng: LatLng? = null
                val status = orderModel?.status
//                if (status == 1) {
//                    val endLat = orderModel?.startCoordinates?.latitude ?: 0.0
//                    val endLng = orderModel?.startCoordinates?.longitude ?: 0.0
//                    if (endLat != 0.0 && endLng != 0.0) {
//                        val end = convert(LatLng(endLat, endLng))
//                        endLatLng = LatLng(end.lat, end.lon)
//                    }
//                } else {
                //导航到乘客的终点
                val endLat = orderModel?.endCoordinates?.y ?: 0.0
                val endLng = orderModel?.endCoordinates?.x ?: 0.0
                if (endLat != 0.0 && endLng != 0.0) {
                    val end = convert(LatLng(endLat, endLng))
                    endLatLng = LatLng(end.lat, end.lon)
                }
                // }
                if (null != endLatLng) {
                    ARouter.getInstance().build(DriverPath.NAVIGATION)
                        .withParcelable("start_point", startLatLng)
                        .withParcelable("end_point", endLatLng)
                        .navigation()
                }
            }
        }

        binding.locate.clickWithTrigger {
            requestLocationService()
        }


    }

    /**谷歌境外坐标系 (WGS-84) 转 火星坐标系(GCJ-02)的转换*/
    private fun convert(latlng: LatLng) =
        GPSConverterUtils.gps84_To_Gcj02(latlng.latitude, latlng.longitude)

    /**
     * 请求定位服务
     */
    private fun requestLocationService() {
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            requestLocationUpdate()
        }
    }

    /**
     * 请求位置更新
     */
    private fun requestLocationUpdate() {
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.myLooper()
        )
    }

    private fun stopLocationUpdate() {
        fusedLocationClient.removeLocationUpdates(locationCallback)
    }


    override fun initObserver(savedInstanceState: Bundle?) {
        super.initObserver(savedInstanceState)

        viewModel?.orderTemplate?.observe(this, Observer { order ->
            orderModel = order

            if (order.type == 2) {
                binding.orderGap.text =
                    TimeUtils.getOverTimeGap(this, order.startTime ?: "")

                val countDownTimer = object : CountDownTimer(60 * 60 * 1000L, 1000L) {
                    override fun onTick(millisUntilFinished: Long) {
                        binding.orderGap.text =
                            TimeUtils.getOverTimeGap(
                                this@OrderReceiveDetailActivity,
                                order.startTime ?: ""
                            )
                    }

                    override fun onFinish() {

                    }
                }.start()
            }

            binding.directions.directionStart.text = order?.startAddress
            binding.directions.directionEnd.text = order?.endAddress

            setTextViewByLimit(
                binding.textView2,
                order?.type == 1,
                getString(R.string.driver_real_time_order),
                getString(R.string.driver_reservation_order)
            )

            setTextViewByLimit(
                binding.options.textView3,
                order?.type == 1,
                getString(R.string.time_real_time),
                getString(R.string.order_create_time, order?.startTime)
            )

            setTextViewValue(
                this,
                binding.options.tunnel,
                R.string.order_tunnel,
                order?.tunnel?.name,
                getString(R.string.what_ever)
            )


//            setTextViewValue(
//                this,
//                binding.options.tip,
//                R.string.order_tip,
//                order?.bountyFee.toString(),
//                "0.00"
//            )
            if(order.bountyFee==null){
                binding.options.tip.text = resources.getString(R.string.driver_tip)+"HK\$ "+"0.00"
            }
            else{
                binding.options.tip.text = resources.getString(R.string.driver_tip)+"HK\$ "+order.bountyFee.toString()+""
            }


            setTextViewValue(
                this,
                binding.options.station,
                R.string.order_station,
                if (order.stationIndex.isNullOrEmpty() || order?.stationIndex == "0") null else order?.stationIndex,
                if (order.stationIndex.isNullOrEmpty() || order?.stationIndex == "0") getString(R.string.what_ever) else null
            )

            setTextViewValue(
                this,
                binding.options.remarks,
                R.string.order_remark,
                order?.remark,
                getString(R.string.none)
            )

            queryRoute()

        })

        viewModel?.orderReceiving?.observe(this, Observer { orderReceiving ->
            progressDialog?.dismiss()
            val code = orderReceiving.code
            when (code) {
                200 ->{
                    ARouter.getInstance().build(DriverPath.ORDER_IN_PROGRESS_DETAIL)
                        .withString("orderId", orderReceiving.data).navigation()
                    DriverDataRepository.getInstance().hasStatusChange().value = true
                    finish();
                }
                1001 ->{
                    Toast.makeText(
                        this,
                        orderReceiving.msg,
                        Toast.LENGTH_LONG
                    ).show()
                }
                1003 ->{
                    Toast.makeText(
                        this,
                        orderReceiving.msg,
                        Toast.LENGTH_LONG
                    ).show()
                }

                400 ->{
                    Toast.makeText(
                        this,
                        getString(R.string.operate_failed_retry),
                        Toast.LENGTH_LONG
                    ).show()
                }
                else -> {
                    Toast.makeText(
                        this,
                        getString(R.string.driver_has_doing_order),
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        })

    }

    /**
     * 请求路线
     */
    private fun queryRoute() {
        viewModel?.getDirection(
            orderModel?.startCoordinates?.y.toString() + "," + orderModel?.startCoordinates?.x,
            orderModel?.endCoordinates?.y.toString() + "," + orderModel?.endCoordinates?.x
        )
    }


    /**
     * 绘制路线到谷歌地图
     */
    private fun drawRoutes(map: GoogleMap) {
        viewModel?.direction?.observe(this, Observer {
            val decodedPath = PolyUtil.decode(it) //来源Google Map Util
            val lineOptions = PolylineOptions()
            lineOptions.addAll(decodedPath) //添加路线
            lineOptions.color(Color.parseColor("#0AC6A2")) //线条设置
            lineOptions.jointType(JointType.ROUND)
            lineOptions.width(15f)
            map.clear()
            map.addPolyline(lineOptions)
            if (decodedPath.size > 2) {
                zoomRoute(map, decodedPath)
                map.addMarker(
                    MarkerOptions().position(decodedPath[0]).icon(
                        BitmapDescriptorFactory.fromResource(
                            R.drawable.ic_start_point
                        )
                    )
                )
                map.addMarker(
                    MarkerOptions().position(decodedPath[decodedPath.size - 1]).icon(
                        BitmapDescriptorFactory.fromResource(R.drawable.ic_end_point)
                    )
                )
                map.setOnCameraIdleListener { }
            }
        })
    }

    /**
     * Zooms a Route (given a List of LalLng) at the greatest possible zoom level.
     *
     * @param googleMap: instance of GoogleMap
     * @param lstLatLngRoute: list of LatLng forming Route
     */
    private fun zoomRoute(googleMap: GoogleMap?, lstLatLngRoute: List<LatLng>?) {

        if (googleMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return;

        val boundsBuilder = LatLngBounds.Builder()
        for (latLngPoint in lstLatLngRoute)
            boundsBuilder.include(latLngPoint)

        val routePadding = 100
        val latLngBounds = boundsBuilder.build()

        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, routePadding));
    }

}